package com.sgb.kjwl.view.ui.activity.material;

import com.google.gson.reflect.TypeToken;
import com.sgb.kjwl.api.APIManager;
import com.sgb.kjwl.api.NewAPIManager;
import com.sgb.kjwl.model.entity.HomeSearchCompanyEntity;
import com.sgb.kjwl.model.entity.ProListEntity;
import com.sgb.kjwl.model.entity.StoreEntity;
import com.sgb.kjwl.model.entity.user.AddressEntity;
import com.sgb.kjwl.model.entity.user.GoodsListEntity;
import com.sgb.kjwl.repository.HomeRepertory;
import com.sgb.kjwl.utils.LocationUtil;
import com.swgk.core.base.BaseViewModel;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.base.model.entity.ListResponse;
import com.swgk.core.mmkvutil.CacheMarker;
import com.swgk.core.mmkvutil.DatalUtils;
import com.swgk.core.mmkvutil.MkvUtils;
import com.swgk.core.util.MToast;

import org.jetbrains.annotations.NotNull;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * @author PC
 */
public class GoodsSearchResultModle extends BaseViewModel {

    private final GoodsSearchResultActivity activity;
    private final HomeRepertory repertory;


    public GoodsSearchResultModle(GoodsSearchResultActivity activity, HomeRepertory repertory) {
        this.activity = activity;
        this.repertory = repertory;
    }

    private int goodsUpPageNum;
    private int goodsDownPageNum;
    private int companyUpPageNum;
    private int companyDownPageNum;
    private int pageSize = 10;


    public void searchByKeywordGoods(String keyWord, String provinceNo, String cityNo, List<String> districtNo, String promoteStatus, String selfSupportTag, boolean isLoadMore) {
        if (isLoadMore) {
            goodsUpPageNum++;
        } else {
            goodsUpPageNum = 1;
        }
        StringBuilder stringBuilder = new StringBuilder();
        if (districtNo != null && districtNo.size() != 0) {
            for (String s : districtNo) {
                stringBuilder.append(",").append(s);
            }
        }
        stringBuilder.replace(0, 1, "");
        Map<String, Object> map = new HashMap<>();
        map.put("pageNum", goodsUpPageNum);
        map.put("pageSize", pageSize);
//        map.put("areaCode", repertory.getAreaCode());
        map.put("keyWord", keyWord);
        map.put("provinceNo", provinceNo);
        map.put("cityNo", cityNo);
        map.put("districtNo", stringBuilder.toString());
        if (!"".equals(promoteStatus)) {
            map.put("promoteStatus", promoteStatus);
        }
        if (!"".equals(selfSupportTag)) {
            map.put("selfSupportTag", selfSupportTag);
        }
        if (LocationUtil.isOpenLocation(activity) && LocationUtil.currentLocationIsValid()) {
            map.put("longitude", String.valueOf(LocationUtil.getCurrentLongitude()));
            map.put("latitude", String.valueOf(LocationUtil.getCurrentLatitude()));
        } else {
            map.put("longitude", "0");
            map.put("latitude", "0");
        }
        NewAPIManager.getInstance().getGoodsReleasedAPI().searchByKeywordGoods(map).enqueue(new Callback<BaseEntity<ProListEntity<List<GoodsListEntity>>>>() {
            @Override
            public void onResponse(Call<BaseEntity<ProListEntity<List<GoodsListEntity>>>> call, Response<BaseEntity<ProListEntity<List<GoodsListEntity>>>> response) {
                if (response.body() != null && response.body().getState() != null && APIManager.RESPONSE_OK.equals(response.body().getState())) {
                    activity.showGoodsUpList(response.body().getData().getList(), isLoadMore, response.body().getData().getTotalRow(), true);
                } else {
                    activity.showGoodsUpList(new ArrayList<>(), isLoadMore, 0, false);
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<ProListEntity<List<GoodsListEntity>>>> call, Throwable t) {
                activity.showGoodsUpList(new ArrayList<>(), isLoadMore, 0, false);
            }
        });
    }

    public void searchByKeywordStore(String keyWord, boolean isLoadMore) {
        if (isLoadMore) {
            companyUpPageNum++;
        } else {
            companyUpPageNum = 1;
        }
        Map<String, Object> map = new HashMap<>();
        map.put("pageNum", companyUpPageNum);
        map.put("pageSize", pageSize);
        map.put("areaCode", repertory.getAreaCode());
        map.put("keyWord", keyWord);
        if (LocationUtil.isOpenLocation(activity) && LocationUtil.currentLocationIsValid()) {
            map.put("longitude", String.valueOf(LocationUtil.getCurrentLongitude()));
            map.put("latitude", String.valueOf(LocationUtil.getCurrentLatitude()));
        } else {
            map.put("longitude", "0");
            map.put("latitude", "0");
        }
        NewAPIManager.getInstance().getGoodsReleasedAPI().searchByKeywordStore(map).enqueue(new Callback<BaseEntity<ProListEntity<List<StoreEntity>>>>() {
            @Override
            public void onResponse(Call<BaseEntity<ProListEntity<List<StoreEntity>>>> call, Response<BaseEntity<ProListEntity<List<StoreEntity>>>> response) {
                if (response.body() != null && response.body().getState() != null && APIManager.RESPONSE_OK.equals(response.body().getState())) {
                    activity.showCompanyUpList(response.body().getData().getList(), isLoadMore, response.body().getData().getTotalRow(), true);
                } else {
                    activity.showCompanyUpList(new ArrayList<>(), isLoadMore, 0, false);
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<ProListEntity<List<StoreEntity>>>> call, Throwable t) {
                activity.showCompanyUpList(new ArrayList<>(), isLoadMore, 0, false);
            }
        });
    }


    public void getAreaData() {
        Type type = new TypeToken<List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>>>() {
        }.getType();
        Object obj = DatalUtils.getInstance().getData(MkvUtils.CacheModular, CacheMarker.AREA_JSON, type);
        if (obj != null) {
            List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> dataList = (List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>>) obj;
            activity.setAddressData(dataList, repertory.getAreaCode());
        } else {
            APIManager.getInstance().getGoodsAPI().getCityList().enqueue(new Callback<BaseEntity<List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>>>>() {
                @Override
                public void onResponse(@NotNull Call<BaseEntity<List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>>>> call, @NotNull Response<BaseEntity<List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>>>> response) {
                    if (response.body() == null) {
                        return;
                    }
                    if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                        activity.setAddressData(response.body().getData(), repertory.getAreaCode());
                    }
                }

                @Override
                public void onFailure(@NotNull Call<BaseEntity<List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>>>> call, @NotNull Throwable t) {
                }
            });
        }
    }


    private Map<String, Object> goodsDownMap(boolean isLoadMore) {
        Map<String, Object> map = new HashMap<>();
        if (isLoadMore) {
            goodsDownPageNum++;
        } else {
            goodsDownPageNum = 1;
        }
        map.put("pageNum", goodsDownPageNum);
        map.put("pageSize", pageSize);
        if (LocationUtil.isOpenLocation(activity) && LocationUtil.currentLocationIsValid()) {
            map.put("lon", String.valueOf(LocationUtil.getCurrentLongitude()));
            map.put("lat", String.valueOf(LocationUtil.getCurrentLatitude()));
        } else {
            map.put("lon", "0");
            map.put("lat", "0");
        }
        map.put("areaCode", repertory.getAreaCode());
        map.put("distanceSort", "0");
        map.put("timeSort", "2");
        map.put("priceSort", "0");
        return map;
    }

    public void getGoodsList(boolean isLoadMore) {
        NewAPIManager.getInstance().getGoodsAPI().getGoodsList(goodsDownMap(isLoadMore)).enqueue(new Callback<BaseEntity<ListResponse<List<GoodsListEntity>>>>() {
            @Override
            public void onResponse(@NotNull Call<BaseEntity<ListResponse<List<GoodsListEntity>>>> call, @NotNull Response<BaseEntity<ListResponse<List<GoodsListEntity>>>> response) {
                if (response.body() != null && response.body().getState() != null && APIManager.RESPONSE_OK.equals(response.body().getState())) {
                    activity.showGoodsDownList(response.body().getData().getList(), isLoadMore);
                } else {
                    if (isLoadMore) {
                        MToast.showToast(activity, "加载失败，请稍后重试");
                    } else {
                        activity.showGoodsDownList(new ArrayList<>(), isLoadMore);
                    }
                }
            }

            @Override
            public void onFailure(@NotNull Call<BaseEntity<ListResponse<List<GoodsListEntity>>>> call, @NotNull Throwable t) {
                if (isLoadMore) {
                    MToast.showToast(activity, "加载失败，请稍后重试");
                } else {
                    activity.showGoodsDownList(new ArrayList<>(), isLoadMore);
                }
            }
        });
    }


    /**
     * 获取供货商列表数据
     *
     * @param isLoadMore
     */
    public void getSupplierListModel(boolean isLoadMore) {
        Map<String, Object> map = new HashMap<>();
        companyDownPageNum = isLoadMore ? companyDownPageNum + 1 : 1;
        map.put("province", repertory.getAreaCode());
        map.put("page", companyDownPageNum);
        map.put("limit", pageSize);
        if (LocationUtil.isOpenLocation(activity) && LocationUtil.currentLocationIsValid()) {
            map.put("longitude", String.valueOf(LocationUtil.getCurrentLongitude()));
            map.put("latitude", String.valueOf(LocationUtil.getCurrentLatitude()));
        } else {
            map.put("longitude", "0");
            map.put("latitude", "0");
        }
        NewAPIManager.getInstance().getGoodsReleasedAPI().getSupplierRecommendation(map).enqueue(new Callback<BaseEntity<ProListEntity<List<HomeSearchCompanyEntity>>>>() {
            @Override
            public void onResponse(Call<BaseEntity<ProListEntity<List<HomeSearchCompanyEntity>>>> call, Response<BaseEntity<ProListEntity<List<HomeSearchCompanyEntity>>>> response) {
                if (response.body() != null && response.body().getState() != null && APIManager.RESPONSE_OK.equals(response.body().getState())) {
                    activity.showCompanyDownList(response.body().getData().getList(), isLoadMore);
                } else {
                    if (isLoadMore) {
                        MToast.showToast(activity, "加载失败，请稍后重试");
                    } else {
                        activity.showCompanyDownList(new ArrayList<>(), isLoadMore);
                    }
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<ProListEntity<List<HomeSearchCompanyEntity>>>> call, Throwable t) {
                if (isLoadMore) {
                    MToast.showToast(activity, "加载失败，请稍后重试");
                } else {
                    activity.showCompanyDownList(new ArrayList<>(), isLoadMore);
                }
            }
        });
    }

    public String getAreaCode() {
        return repertory.getAreaCode();
    }
}
